package com.quanjiaolian.userinfo.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.quanjiaolian.login.service.LoginService;
import com.quanjiaolian.login.serviceimpl.LoginServiceImpl;
import com.quanjiaolian.tools.ResponseToJson;
import com.quanjiaolian.tools.SendTemplateSMS;
import com.quanjiaolian.userinfo.service.UserInfoService;
import com.quanjiaolian.userinfo.serviceimpl.UserInfoServiceImpl;
/**
 * 处理用户修改绑定手机请求
 * @author Herson_Li
 *
 */
@SuppressWarnings("serial")
public class UpdateBindingMsisdn extends HttpServlet {

	/**
	 * 声明Log4j变量
	 */
	public static ResourceBundle resourceBundle = null;
	static Logger logger = Logger.getLogger(UpdateBindingMsisdn.class.getName());
	UserInfoService uis = new UserInfoServiceImpl(); 
	Map<String,Object> resultMap = new HashMap<String,Object>();
	LoginService ls = new LoginServiceImpl();
	/**
	 * 向用户下发短信验证码
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String msisdn = request.getParameter("msisdn");
		String user_type = request.getParameter("user_type");
		if("".equals(msisdn) || msisdn == null){
			resultMap.put("result","Error");
		}else if("".equals(user_type) || msisdn == null){
			resultMap.put("result","Error");
		}else{
			int i = ls.isRegister(msisdn, user_type);
			if(i>0){
				resultMap.put("result","this msisdn has been bound");
			}else{
				Map<String,Object> map = SendTemplateSMS.sendSMS(msisdn);
				resultMap.put("result",map);
			}
		}
		
		ResponseToJson.responseOutWithJson(response, resultMap);
	}

	/**
	 * 修改用户绑定手机号
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String new_msisdn = request.getParameter("new_msisdn");
		String user_type = request.getParameter("user_type");
		String user_id = request.getParameter("user_id");
		if(new_msisdn == null || "".equals(new_msisdn)){
			resultMap.put("result","Error");
		}else if(user_type == null || "".equals(user_type)){
			resultMap.put("result","Error");
		}else if(user_id == null || "".equals(user_id)){
			resultMap.put("result","Error");
		}else{
			try{
				int i = uis.updateBinddingMsisdn(new_msisdn,user_type,user_id);
				if(i>0){
					resultMap.put("result","OK");
				}else{
					resultMap.put("result","Failed");
				}
			}catch (Exception e) {
				resultMap.put("result","Error");
				logger.info(e);
				e.printStackTrace();
			}
			
		}
		ResponseToJson.responseOutWithJson(response, resultMap);
	}

}
